import router from "@/router";
import { useUserStoreHook } from "@/store/modules/user";
import { usePermissionStoreHook } from "@/store/modules/permission";

import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false }); // 进度条

const permissionStore = usePermissionStoreHook();
const userStore = useUserStoreHook();

const hasToken = localStorage.getItem("pinia_token") || userStore.pinia_token;

async function initMenu() {
  if (hasToken) {
    const rolesList = await userStore.getUserInfo();
    const accessRoutes = await permissionStore.generateRoutes(rolesList);
    accessRoutes.forEach((route) => {
      router.addRoute(route);
    });
  }
}

// 白名单路由
const whiteList = ["/login"];

export const setupRouterHooks = async () => {
  await initMenu();
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const hasToken =
      localStorage.getItem("pinia_token") || userStore.pinia_token;
    if (hasToken) {
      if (to.path === "/login") {
        // 如果已登录，跳转首页
        next({ path: "/" });
        NProgress.done();
      } else {
        // 未匹配到任何路由，跳转404
        if (to.matched.length === 0) {
          from.path ? next({ path: from.path }) : next("/404");
        } else {
          next();
        }
      }
    } else {
      // 未登录可以访问白名单页面
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });
};
